<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()" />
    <van-search
      v-model="value"
      @search="
        $router.push({ path: '/searchResult', query: { keyword: value } })
      "
      @input="onInput"
      show-action
      placeholder="请输入搜索关键词"
    >
      <template #action>
        <div
          @click="
            $router.push({ path: '/searchResult', query: { keyword: value } })
          "
        >
          搜索
        </div>
      </template>
    </van-search>
    <van-cell-group
      v-for="(item, index) in changeGo"
      :key="index"
      @click="
        $router.push({
          path: '/searchResult',
          query: { keyword: changeList[index] }
        })
      "
    >
      <van-cell icon="search">
        <template #title>
          <div v-html="item"></div>
        </template>
      </van-cell>
    </van-cell-group>
    <van-cell value="历史记录" />
    <van-cell-group>
      <van-cell v-for="(item, index) in allHistory" :key="index" :title="item">
        <template #right-icon>
          <van-icon name="close" class="search-icon" />
        </template>
      </van-cell>
      <van-cell>
        <div class="clear" @click="onHistory">清除历史记录</div>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { searchSuggestionList, getSearchAll, deleteSearchAll } from "./home.js";
export default {
  name: "search",
  data() {
    return {
      value: "",
      changeList: [],
      timeId: null,
      allHistory: []
    };
  },
  async created() {
    let res = await getSearchAll();
    this.allHistory = res.data.data.keywords;
  },
  methods: {
    onInput() {
      // 函数的防抖  一般用于输入框事件
      clearTimeout(this.timeId);
      this.timeId = setTimeout(async () => {
        if (this.value == "") {
          this.changeList = [];
          return;
        }
        let res = await searchSuggestionList(this.value);
        this.changeList = res.data.data.options;
      }, 300);
    },
    async onHistory(item) {
      let res = await deleteSearchAll({ message: item });
      console.log(res);
      if (res.status == 204) {
        this.$toast.success("删除成功");
        this.historyList = [];
      } else {
        this.$toast.fail("删除失败");
      }
    }
  },
  computed: {
    //   搜索文字高亮
    changeGo() {
      let reg = new RegExp(this.value, "gi");
      return this.changeList.map(value => {
        return value.replace(
          reg,
          macth => `<span style="color:red">${macth}</span>`
        );
      });
    }
  }
};
</script>

<style lang="less">
.clear {
  text-align: center;
}
</style>
